<?php

/****微信开发相关文档*****/

/**
 * Created by PhpStorm.
 * User: 曹文
 * Date: 2016/12/21
 * Time: 9:53
 */



/******** curl及协议相关相关 ********/

//curl第一套
function curl_https($url, $data=array(), $header=array(), $timeout=30){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    $response = curl_exec($ch);
    if($error=curl_error($ch)){
        die($error);
    }
    curl_close($ch);
    return $response;
}


//curl 第二套
function https_request($url,$data = null){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}


//第三套curl post
function http_post_data($url, $data_string) {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    curl_exec($ch);
    if (curl_errno($ch)) {
        $this->ErrorLogger('curl falied. Error Info: '.curl_error($ch));
    }
    $return_content = ob_get_contents();
    ob_end_clean();
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return array($return_code, $return_content);
}



/******** 微信开放平台相关 ********/

/**
 * @param $appid : appid 开发者应用获取秘钥
 * @param $secret : secret 开发者应用获取密匙
 * @param $backurl : 回调地址
 * @param $code : 授权获取
 * @return mixed
 */


//生成授权链接 开放平台
function url($appid,$backurl){
    $redirect_uri=urlencode($backurl);
    return $url='https://open.weixin.qq.com/connect/qrconnect?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect';
}


//生成静默授权链接 开放平台  获取$code
function c_url($appid,$backurl){
    $redirect_uri=urlencode($backurl);
    return $url='https://open.weixin.qq.com/connect/qrconnect?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base &state=STATE#wechat_redirect';
}


//    具体信息
function aget_uersa($code,$appid,$secret){
    $refresh_token=get_tokenrefresh($code,$appid,$secret);
    $access_token=$refresh_token['access_token'];
    $openid=$refresh_token['openid'];
    $url ="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
    return json_decode(curl_https($url),true);
}



function aget_access_token($code,$appid,$secret){
//    $appid='wx6b718244a3259af0';
//    $secret='a7f11fc99815a6c46f158aea9e2a8b0c';
    $url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
    return json_decode(curl_https($url),true);
}



//       7天权限刷新access_token
function aget_tokenrefresh($code,$appid,$secret){
    $refresh_token=get_access_token($code,$appid,$secret);
    $raa=$refresh_token['refresh_token'];
//        var_dump($refresh_token);
//    $appid='wx6b718244a3259af0';
    return json_decode(curl_https("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$appid."&grant_type=refresh_token&refresh_token=".$raa),true);
}



/******** 微信公众平台相关 ********/

/**
 * @param $appid : appid 开发者应用获取秘钥
 * @param $secret : secret 开发者应用获取密匙
 * @param $backurl : 回调地址
 * @param $code : 授权获取 内含openid
 * @param $jsonmenu: 菜单具体
 * @return mixed
 */


//公众号网页生成授权链接 伪snsapi_base  真 snsapi_userinfo   获取$code
function wxurl ($appid,$backurl){
    $redirect_uri=urlencode($backurl);
    return $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
';
}



//10分钟权限
function get_access_token($code,$appid,$secret){
    $url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
    return json_decode(curl_https($url),true);
}



//       7天权限刷新access_token
function get_tokenrefresh($code,$appid,$secret){
    $refresh_token=get_access_token($code,$appid,$secret);
    $raa=$refresh_token['refresh_token'];
//        var_dump($refresh_token);
    return json_decode(curl_https("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$appid."&grant_type=refresh_token&refresh_token=".$raa),true);
}



//   具体信息
function get_uersa($code,$appid,$secret){
    $refresh_token=get_tokenrefresh($code,$appid,$secret);
    $access_token=$refresh_token['access_token'];
    $openid=$refresh_token['openid'];
    $url ="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
    return json_decode(curl_https($url),true);
}



//自定义菜单中access_token
function menuaccess_token($appid,$secret){
    $get_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
    $output = https_request($get_access_token_url);
    $jsoninfo = json_decode($output, true);
    $access_token = $jsoninfo["access_token"];
    return $access_token;
}

//自定义菜单
function create_menu($appid,$secret,$jsonmenu){
    $access_token=menuaccess_token($appid,$secret);
    $post_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
    $result = https_request($post_menu_url,$jsonmenu);
    $json = json_decode($result, true);
    if($json["errcode"] == 0 & $json["errmsg"] == 'ok'){
        echo "<script>";
        echo "alert('您的自定义菜单添加成功！请关闭界面')";
        echo "</script>";
//        responseMsg();
    }else{
        echo "<script>";
        echo "alert('你的自定义菜单添加失败,请查看您的参数')";
        echo "</script>";
    }
}


//获取二维码ticket
function rq_ticket($appid,$secret,$fqid){
    $access_token=menuaccess_token($appid,$secret);
    $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
//    echo $url.'<br/>';
    $qrcode= '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$fqid.'}}}';
//    echo $qrcode;
    $result = http_post_data($url,$qrcode);
    $oo = json_decode($result[1]);
    $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";
    $url = $qrcode_get_url.'ticket='.$oo->ticket.'';
    return $url;
}


//自动生成回复信息,及生成名片
function responseMsg()
{
//    create_menu($appid,$secret,$jsonmenu);//创建菜单

    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//    $postStr = file_get_contents("php://input");
    //返回回复数据
    if (!empty($postStr))
    {
        $path='/wx.txt';
        @chmod('/wx.txt',0777);
        echo file_put_contents($path,'2');
        if (file_exists($path)){
            echo "ok";
        }else{
            echo "ng";
        }
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;//发送消息方ID
        $toUsername = $postObj->ToUserName;//接收消息方ID
        $keyword = trim($postObj->Content);//用户发送的消息
        $times = time();//发送时间
        $MsgType = $postObj->MsgType;//消息类型
        $msgType = "text";
        if($MsgType =='event')
        {
            $MsgEvent = $postObj->Event;//获取事件类型
            if ($MsgEvent=='subscribe')
            {
                //订阅事件
            }
            elseif ($MsgEvent=='CLICK')
            {
                //点击事件
                $EventKey = $postObj->EventKey;
                //菜单的自定义的key值，可以根据此值判断用户点击了什么内容，从而推送不同信息
                switch($EventKey)
                {
                    case "VCX_JOBINFORMATION" :
                        //要返回相关内容
                        $content = "请输入你的订单号";
                        break;
                    case "VCX_JOBINFORMATIOO" :
                        //要返回相关内容
                        $content = "请输入你的姓名";
                        break;
                }

            }
        }
        $textTpl = "<xml>
       <ToUserName><![CDATA[%s]]></ToUserName>
       <FromUserName><![CDATA[%s]]></FromUserName>
       <CreateTime>%s</CreateTime>
       <MsgType><![CDATA[%s]]></MsgType>
       <Content><![CDATA[%s]]></Content>
       <FuncFlag>0</FuncFlag>
       </xml>";
//        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $times, "text", "这里是要说的内容");
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $times, "text", $content);

    }
    else
    {
        $path='/wx.txt';
        @chmod('/wx.txt',0777);
        echo file_put_contents($path,'1');
        if (file_exists($path)){
            {echo "ok";}
        }else{
            echo "ng";
        }
    }
}


/**
 *@param type: text 文本类型, news 图文类型
 *@param value_arr array(内容),array(ID)
 *@param o_arr array(array(标题,介绍,图片,超链接),...小于10条),array(条数,ID)
 */

function make_xml($type,$value_arr,$o_arr=array(0),$fromUsername,$toUsername,$times){
    //=================xml header============
    $con="<xml>
                    <ToUserName><![CDATA[{$fromUsername}]]></ToUserName>
                    <FromUserName><![CDATA[{$toUsername}]]></FromUserName>
                    <CreateTime>{$times}</CreateTime>
                    <MsgType><![CDATA[{$type}]]></MsgType>";

    //=================type content============
    switch($type){

        case "text" :
            $con.="<Content><![CDATA[{$value_arr[0]}]]></Content>
                    <FuncFlag>{$o_arr}</FuncFlag>";
            break;

        case "news" :
            $con.="<ArticleCount>{$o_arr[0]}</ArticleCount>
                     <Articles>";
            foreach($value_arr as $id=>$v){
                if($id>=$o_arr[0]) break; else null; //判断数组数不超过设置数
                $con.="<item>
                         <Title><![CDATA[{$v[0]}]]></Title>
                         <Description><![CDATA[{$v[1]}]]></Description>
                         <PicUrl><![CDATA[{$v[2]}]]></PicUrl>
                         <Url><![CDATA[{$v[3]}]]></Url>
                         </item>";
            }
            $con.="</Articles>
                     <FuncFlag>{$o_arr[1]}</FuncFlag>";
            break;
    } //end switch
    //=================end return============
    $con.="</xml>";
    return $con;
}
















//    public function menuaccess_token($appid,$secret){
//        $get_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
//        $output = $this->https_request($get_access_token_url);
//        $jsoninfo = json_decode($output, true);
//        $access_token = $jsoninfo["access_token"];
//        return $access_token;
//    }
//    public function rq_ticket($appid,$secret,$id){
//        $access_token = $this->menuaccess_token($appid,$secret);
//        $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
//        $qrcode ='{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
//        $result = $this->http_post_data($url,$qrcode);
//        $oo = json_decode($result[1]);
//        $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";
//        $url = $qrcode_get_url.'ticket='.$oo->ticket.'';
//        return $url;
//    }
//    public function https_request($url,$data = null){
//        $curl = curl_init();
//        curl_setopt($curl, CURLOPT_URL, $url);
//        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
//        if (!empty($data)){
//            curl_setopt($curl, CURLOPT_POST, 1);
//            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//        }
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//        $output = curl_exec($curl);
//        curl_close($curl);
//        return $output;
//    }
//    public function http_post_data($url, $data_string) {
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_POST, 1);
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//                'Content-Type: application/json; charset=utf-8',
//                'Content-Length: ' . strlen($data_string))
//        );
//        ob_start();
//        curl_exec($ch);
//        if (curl_errno($ch)) {
//            $this->ErrorLogger('curl falied. Error Info: '.curl_error($ch));
//        }
//        $return_content = ob_get_contents();
//        ob_end_clean();
//        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//        return array($return_code, $return_content);
//    }



























//获取凭据access_token
function token_($member_id){
    $user_service = new UserService();
    $user = $user_service->get_user($member_id);
    $appid = $user['app_id'];
    $app_secret = $user['app_secret'];

    $ret = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$app_secret.'');
    $ret = json_decode($ret,true);
    return $ret['access_token'];
}
//生成二维码
function qrcode($member_id,$id){
//        $data = '{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
//        $ret = $this->p_post('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->at($member_id),$data);
//        $ret = json_decode($ret,true);

//        return urldecode($ret['url']);
    //根据ticket获取图片
//        $img = file_get_contents('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.UrlEncode($ret['ticket']));
//        file_put_contents("DZP".$id."png",$img);
//        $token_ = $this->token_($member_id);
    $token_ = '6_XLOdoPdxV6NX55y9-TR_1oQ5fehv0Q-eSOh2teHoSv7-_itdBb6Dj9U2G0EuVJ-MLq4Gn4GCnxsTT4P9CSFtjO_wn5cOwbmB4kfrYVJeRYQuEKnCwC_r9qmz84LwxYVrN0orQQd4eNgdPOMBYJBhAJASDV';
    $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="'.$token_.'"';
    $qrcode ='{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
    $result = $this->api_notice_increment($url, $qrcode);
    $result = json_decode($result, true);
    var_dump($result);exit();
    return urldecode($result);
}
function api_notice_increment($url, $data){
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        curl_close( $ch );
        return $ch;
    }else{
        curl_close( $ch );
        return $tmpInfo;
    }
}
//模拟post请求,既可以是http也可以是https
function p_post($url,$data,$https=true){
    $curl = curl_init(); //启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    if($https){
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检测
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); //从证书中检查SSL加密算法是否存在
    }
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_POST, 1); //发送一个常规的post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); //post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); //设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); //显示返回的header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); //执行操作
    curl_close($curl); //关闭curl会话
    return $tmpInfo; //返回数据
}